package com.test;

import java.io.*;
import java.util.*;

//线程池的定义
public class GZipAllFiles {
	// 定义工作线程数
	public final static int THREAD_COUNT = 4;
	// 带压缩文件数
	private static int filesToBeCompressed = -1;
	
	public static void main(String[] args) {
		// 定义池对象
		Vector<File> pool = new Vector<File>();
		// 定义工作线程数组
		GZipRunnable[] threadRuns = new GZipRunnable[THREAD_COUNT];
		Thread[] threads = new Thread[THREAD_COUNT];
		// 初始化工作线程，并启动工作线程
		for (int i = 0; i < threads.length; i++) {
			threadRuns[i] = new GZipRunnable(pool);
			threads[i] = new Thread(threadRuns[i]);
			threads[i].start();
		}
		int totalFiles = 0;
		for (int i = 0; i < args.length; i++) {
			File f = new File(args[i]);
			if (f.exists()) {
				// 遍历指定文件目录
				if (f.isDirectory()) {
					File[] files = f.listFiles();
					for (int j = 0; j < files.length; j++) {
						if (!files[j].isDirectory()) { // don't recurse
							// directories
							totalFiles++;
							// 同步存放待压缩文件对象的任务池
							synchronized (pool) {
								// 向任务池中添加任务
								pool.add(0, files[j]);
								// 唤醒等待线程
								pool.notifyAll();
							}
						}
					}
				} //
				else {
					totalFiles++;
					// 同步存放待压缩文件对象的任务池
					synchronized (pool) {
						// 向任务池中添加任务
						pool.add(0, f);
						// 唤醒等待线程
						pool.notifyAll();
					}
				}
			} // end if
		} // end for
		filesToBeCompressed = totalFiles;
		// make sure that any waiting thread knows that no
		// more files will be added to the pool
		for (int i = 0; i < threads.length; i++) {
			threads[i].interrupt();
		}
	}

	public static int getNumberOfFilesToBeCompressed() {
		return filesToBeCompressed;
	}
	
}
